<template>
  <q-page
    class="q-pa-md wrapBox"
    v-loading="
      loading || platformUploadStore.platformUploadLoading.beforeStartUploading
    "
  >
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image
            src="/svgs/titleIcon.svg"
            style="width: 17px; margin-top: 2px"
            fit
          />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'dataset' }"
          >数据集
        </el-breadcrumb-item>
        <el-breadcrumb-item
          ><span style="color: #333">新建数据集</span></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="title">新建数据集</div>
      <div class="contentBox">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm typeBox"
          style="max-width: 50%"
          status-icon
        >
          <el-form-item label="数据集名称：" prop="title">
            <el-input
              v-model.trim="ruleForm.title"
              placeholder="请输入数据集名称"
              show-word-limit
              spellcheck="false"
            />
          </el-form-item>
          <el-form-item label="数据集说明：" prop="description">
            <el-input
              v-model.trim="ruleForm.description"
              type="textarea"
              spellcheck="false"
              placeholder="请输入"
              :rows="5"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>
          <el-form-item
            label="数据类型："
            prop="dataset_type"
            style="margin: 0"
          >
            <el-radio-group v-model="tabPosition" @change="handleRadioChange">
              <el-radio-button label="Sequence">序列/结构文件</el-radio-button>
              <el-radio-button label="Image">图片</el-radio-button>
              <el-radio-button label="TimeSeries">时序数据</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin: 0" v-if="tabPosition === 'Sequence'">
            <p style="margin: 0; font-size: 13px">
              支持序列文件: fasta、支持蛋白结构文件: pdb
            </p>
          </el-form-item>
          <el-form-item
            style="margin-top: 10px"
            label="数据上传："
            prop="file_ids"
            ref="imageOfFrom"
          >
            <el-tabs
              :tab-position="tabPosition"
              style="display: flex; flex-direction: column"
              class="demo-tabs"
            >
              <div
                v-for="item in datasetType"
                :key="item.type"
                class="row labelTypeBox"
                v-show="tabPosition == item.type"
                style="flex-direction: column"
              >
                <box-loading v-if="boxLoadState"></box-loading>
                <el-upload
                  class="upload-demo uploadBox"
                  drag
                  :auto-upload="false"
                  multiple
                  style="width: 350px"
                  :on-change="handleFileChange"
                  :before-remove="handleFileRemove"
                  :fileList="platformUploadStore.vueUploadComponentFileList"
                >
                  <div class="el-upload__text uploadBoxBtn">
                    <el-image :src="imgUrl" fit />
                    <div style="color: #333333; font-size: 14px">
                      点击选择文件或将文件拖拽到这里上传
                    </div>
                    <div>支持上传文件格式：{{ item.format }}</div>
                  </div>
                </el-upload>
                <!--                <el-upload class="upload-demo uploadBox" drag :show-file-list="false" :http-request="uploadFile"-->
                <!--                           :file-list="uploadFileList" :before-upload="checkFileType" multiple-->
                <!--                           :on-change="handleFileChanged"-->
                <!--                           :on-remove="removeListData"-->
                <!--                           style="width: 350px;height: 222px;background-color: #d9d9d9!important;">-->
                <!--                  <div class="el-upload__text uploadBoxBtn">-->
                <!--                    <el-image :src="imgUrl" fit/>-->
                <!--                    <div style="color: #333333;font-size: 14px">点击选择文件或将文件拖拽到这里上传</div>-->
                <!--                    <div>支持上传文件格式：{{ item.format }}</div>-->
                <!--                  </div>-->
                <!--                </el-upload>-->
                <div
                  style="width: 280px"
                  :class="{ listOverflowScroll: uploadFileList.length > 4 }"
                >
                  <ul class="el-upload-list el-upload-list--text">
                    <li
                      class="el-upload-list__item is-success"
                      v-for="(item, index) in uploadFileList"
                      :key="index"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <a
                        class="el-upload-list item-name"
                        style="
                          width: 80%;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                        "
                      >
                        <i class="el-icon-document"> </i>
                        {{ item.row_name }}
                      </a>
                      <el-icon
                        style="margin-top: 5px"
                        @click="handleRemove(index)"
                      >
                        <Close />
                      </el-icon>
                    </li>
                  </ul>
                </div>
              </div>
            </el-tabs>
          </el-form-item>
          <el-form-item label="输入版本号：" prop="version">
            <el-input
              v-model.trim="ruleForm.version"
              spellcheck="false"
              placeholder="请输入版本号,例: v1、v001"
            />
          </el-form-item>
        </el-form>
      </div>
      <div
        class="row"
        style="
          display: flex;
          justify-content: flex-end;
          margin: 10px 0 0 0;
          padding: 10px 0;
          background-color: #fff;
        "
      >
        <el-button
          v-if="!store.quickStart.quickFlow"
          @click="resetForm(ruleFormRef)"
          style="background-color: #fff !important"
          >取消
        </el-button>
        <el-button
          v-if="!store.quickStart.quickFlow"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          完成
        </el-button>
        <el-button
          v-if="store.quickStart.quickFlow"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          下一步
        </el-button>
      </div>
    </div>
  </q-page>
</template>
<script setup lang="ts">
import imgUrl from 'assets/dataSet/grayUpload.png';
import type {
  FormInstance,
  FormRules,
  UploadFile,
  UploadFiles,
} from 'element-plus';
import { ElMessage } from 'element-plus';
import { Awaitable } from 'element-plus/es/utils';
import { getDatalabelListApi } from 'src/api/common';
import { createDataset } from 'src/api/dataCenter';
import { getDatasetType, validateDatasetListTitle } from 'src/api/dataset';
import { putQuickStartFlow } from 'src/api/project';
import { dataSetStore } from 'src/stores/dataSet';
import {
  CurrentDataset,
  usePlatformUploadStore,
} from 'src/stores/platform-upload';
import { onMounted, reactive, ref, shallowRef } from 'vue';
import { useRouter } from 'vue-router';
// import {validateModelName} from "src/api/model";

const store = dataSetStore();
const platformUploadStore = usePlatformUploadStore();
const fileType = ref();
const uploadFileList: any = ref([]);
const router = useRouter();
// const vueUploadComponentFileList = ref<UploadUserFile[]>([])
const projectId = router.currentRoute.value.params.project_id;
const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  title: '',
  description: '',
  dataset_type: '',
  version: '',
});

onMounted(() => {
  platformUploadStore.setVueUploadComponentFileListEmpty();
});

const labelSate = ref('false');
const loading = ref(true);
const imageOfFrom = ref();
let datasetType = ref([]);
// 图片
let imgOption: any = ref([]);
// 标注场景时序数据
let dataOption: any = ref([]);
// 标注场景文本
let textOption: any = ref([]);

const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('数据集名称不能为空'));
    return;
  }
  if (value.length < 4) {
    callback(new Error('字段长度最小长度为4'));
    return;
  }
  if (value.length > 16) {
    callback(new Error('字段长度最大长度为16'));
    return;
  }
  let params = {
    title: ruleForm.title,
  };
  validateDatasetListTitle(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};

const rules = reactive<FormRules>({
  title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
  dataset_type: [
    {
      required: true,
      message: '请选择数据类型',
      trigger: 'blur',
    },
  ],
  version: [
    { required: true, message: '输入版本号', trigger: ['blur', 'change'] },
  ],
});
const tabPosition = ref('Sequence');

interface DatasetType {
  type: string;
  format: string;
}

const checkFileType = (
  f: UploadFile
): Awaitable<void | undefined | null | boolean | File | Blob> => {
  const dataList: DatasetType[] = datasetType.value;
  const filterDataList = dataList.filter(
    (item: DatasetType) => item.type === tabPosition.value
  );
  const suffix = filterDataList[0].format;
  const fileSplitArr = f.name.split('.');
  const fileType = fileSplitArr[fileSplitArr.length - 1];

  if (!suffix.includes(fileType)) {
    ElMessage.warning(
      `上传类型错误，请选择${filterDataList[0].format}格式文件`
    );
    return false;
  }

  if ((f.size as number) > platformUploadStore.platformMaxFileSize) {
    ElMessage.warning(`上传文件过大，请选择小于2G的文件`);
    return false;
  }
  return true;
};

const checkFileRepeat = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  for (const file of platformUploadStore.vueUploadComponentFileList) {
    if (uploadFile.name === file.name) {
      ElMessage.warning(file.name + '该文件已存在');
      return false;
    }
  }
  return true;
};

const handleFileRemove = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
): Awaitable<boolean> => true;

const handleFileChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  //element-plus/packages/components/upload/src/use-handlers.ts  87
  if (!checkFileType(uploadFile) || !checkFileRepeat(uploadFile, uploadFiles)) {
    uploadFiles.pop();
    return;
  }

  platformUploadStore.setFileList(uploadFiles);
};

onMounted(() => {
  getDatasetType().then((res: any) => {
    let imageIndex = res.data.findIndex((v: any) => {
      return v.type == 'Image';
    });
    let sequenceIndex = res.data.findIndex((v: any) => {
      return v.type == 'Sequence';
    });
    let timeSeriesIndex = res.data.findIndex((v: any) => {
      return v.type == 'TimeSeries';
    });

    datasetType.value = [
      res.data[sequenceIndex],
      res.data[imageIndex],
      res.data[timeSeriesIndex],
    ] as any;
  });
});

//数据类型切换
function handleRadioChange(value: any) {
  uploadFileList.value = [];
  imageOfFrom.value.clearValidate();
  // ruleForm.file_ids = [];
}

//点击上传
const paramObj = shallowRef();
const boxLoadState = ref(false);
const checkState = ref(false);
const emits = defineEmits(['formData']);

// function uploadFile(obj: any) {
//   imageOfFrom.value.clearValidate();
//   paramObj.value = new FormData();
//   paramObj.value.append('file', obj.file);
//   paramObj.value.append('date', obj.file.name);
//   checkState.value = true;
//   boxLoadState.value = true;
//   uploadFileApi(paramObj.value).then((res) => {
//     uploadFileList.value.push(res.data);
//     ruleForm.file_ids.push(res.data.id);
//     checkState.value = false;
//     boxLoadState.value = false;
//   });
// }

// 对象数组去重
const filterArr = (arr: any) => {
  const uniqueArr = arr.reduce((unique: any, item: any) => {
    if (!unique.some((obj: any) => obj.value === item.value)) {
      unique.push(item);
    }
    return unique;
  }, []);
  return uniqueArr;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  ruleForm.dataset_type = tabPosition.value;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      platformUploadStore.platformUploadLoading.beforeStartUploading = true;
      try {
        const datasetResponse = await createDataset(
          projectId as string,
          ruleForm
        );
        const currentCreatedDataset: CurrentDataset = {
          id: datasetResponse.data.dataset_id,
          title: ruleForm.title,
          version_id: datasetResponse.data.version_id,
          project_id: projectId as string,
          version_title: ruleForm.version,
        };
        if (store.quickStart.quickFlow) {
          loading.value = true;
          putQuickStartFlow(projectId, { stage: 2 }).finally(() => {
            router.push({
              name: 'quick-start',
              params: { project_id: projectId },
            });
          });
        } else {
          loading.value = false;
          await platformUploadStore.startUploadPrepare(currentCreatedDataset);

          await router.push({
            name: 'dataset',
            params: { project_id: projectId },
          });

          await platformUploadStore.startUploadStart(currentCreatedDataset);
        }
      } catch (err) {
        ElMessage.error('创建数据集失败');
        return;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push({ name: 'dataset', params: { project_id: projectId } });
};
initOption();

function initOption() {
  loading.value = true;
  getDatalabelListApi().then((res) => {
    imgOption.value = filterType(res.data, 'Image');
    dataOption.value = filterType(res.data, 'TimeSeries');
    textOption.value = filterType(res.data, 'Text');
    loading.value = false;
  });
}

function filterType(arr: any, str: string) {
  let newArr = arr.filter((item: any, index: number) => {
    if (item.data_type == str) return item;
  });
  return newArr;
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: #f6f8fa;
  height: 46px;

  ::v-deep .el-breadcrumb {
    display: flex;
    align-items: center;
  }
}

.wrapBox {
  padding: 0 !important;

  .datasetBox {
    margin: 0 20px;

    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//间距
.el-form-item {
  margin-bottom: 20px;
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 12px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}

//面包屑中的文字颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}

::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}

::v-deep .el-radio-button__inner {
  width: 150px !important;
  background: #fafafa !important;
}

::v-deep .el-upload-dragger {
  background-color: #fafafa !important;
  border-radius: 0 !important;
}

//::v-deep .upload-demo {
//  height: 175px !important;
//}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #cccccc;
  font-size: 14px;
  font-weight: 400;
}

::v-deep .el-radio-button__original-radio:checked + .el-radio-button__inner {
  background: #3d5ce41a !important;
  color: #3d5ce4 !important;
}

.listOverflowScroll {
  height: 200px;
  overflow: scroll;
}

.labelTypeBox {
  .el-radio-button {
    margin-right: 20px;
    margin-top: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
    }

    &::v-deep
      .el-radio-button__original-radio:checked
      + .el-radio-button__inner {
      background-color: white;
      color: #3d5ce4;
      border-color: #3d5ce4;
      border-left: 1px solid #3d5ce4;
      box-shadow: none;
    }
  }
}

.labelTypeBoxText,
.labelTypeBoxData {
  width: 70vw;

  .el-image {
    width: 100px;
    height: 80px;
  }

  .el-radio-button {
    margin-right: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
      font-size: 12px;
    }
  }
}

.colorBox {
  display: flex;
  flex-wrap: wrap;
  width: 50px;
}

.uploadBox {
  :deep(.el-upload-list) {
    max-height: 120px;
  }

  .uploadBoxBtn {
    text-align: center;

    .el-image {
      width: 56px;
      height: 56px;
      display: block;
      margin: 0 auto;
    }

    div {
      font-size: 12px;
      height: 20px;
    }
  }
}
</style>
